package com.n.passwordbook.LaunchWindow;

import com.n.passwordbook.MainWindow.MainWindow;
import com.n.passwordbook.PasswordBook.PasswordBook;
import com.n.passwordbook.Utils.CryptographyHelper;
import com.n.passwordbook.Utils.Settings;
import com.n.passwordbook.Utils.WindowHelper;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.PasswordField;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Text;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;

public class SetPasswordPage
{
    @FXML
    public Text txt_passwordDifferent;
    @FXML
    public PasswordField pb_password;
    @FXML
    public PasswordField pb_passwordSure;

    private void checkIfPasswordIsSame()
    {
        if (StringUtils.isNotEmpty(pb_password.getText()) && pb_password.getText().equals(pb_passwordSure.getText()))//上下密码相同
        {
            CryptographyHelper.setPBKey(pb_password.getText());
            try
            {
                String fullPath = TmpDataHelper.Path + CryptographyHelper.encryptStringByAES256(TmpDataHelper.UserName, PasswordBook.PBKey) + ".pb";
                PasswordBook.setPasswordBook(pb_password.getText(), TmpDataHelper.UserName, fullPath);
                if (PasswordBook.savePasswordBook() == null) return;
                Settings.setPasswordBookPath(new File(fullPath));
                Settings.saveSettingsFile();
                pb_password.setText("");
                pb_passwordSure.setText("");
                TmpDataHelper.clearAllData();
                TmpDataHelper.MainWindowPreloadThread.join();
                WindowHelper.changeMainSceneRootWithFadeOutAndFadeIn(TmpDataHelper.MainWindowLoader,
                        MainWindow::initializeControllerManually,TmpDataHelper.MainWindowRoot);
            }
            catch (IOException | InterruptedException ioException)
            {
                ioException.printStackTrace();
            }
        }
        else
        {
            txt_passwordDifferent.setOpacity(1);
        }
    }

    public void pbCheckpasswordissame(KeyEvent e)
    {
        checkIfPasswordIsSame();
    }
}
